import { getAfterSalesNeedInfoDetailById } from '@/services/sales/salesNeedInfo';
import {
  addTechnicalsSupport,
  addTechnicalSupport,
  engineerList,
  getTechnicalSupportsById,
  updateTechnicalsSupport,
  updateTechnicalSupport,
} from '@/services/sales/technicalSupport';
import { CloseCircleOutlined } from '@ant-design/icons';
import type { FormListActionType, ProFormInstance } from '@ant-design/pro-components';
import { ProCard, ProFormList } from '@ant-design/pro-components';
import ProForm, { ProFormSelect, ProFormSwitch, ProFormTextArea } from '@ant-design/pro-form';
import { FooterToolbar, PageHeaderWrapper } from '@ant-design/pro-layout';
import { Button, Card, Col, Form, message, Popover, Row } from 'antd';
import React, { useEffect, useRef, useState } from 'react';
import { history, useAccess, useLocation, useModel } from 'umi';
import styles from './style.less';

import { afterSalesNeedList } from '@/services/sales/salesNeedInfo';
import FormItem from 'antd/es/form/FormItem';

interface TableFormDateType {
  id: string;
  workId?: string;
  name?: string;
  department?: string;
  isNew?: boolean;
  editable?: boolean;
}

const fieldLabels = {
  name: '仓库名',
  url: '仓库域名',
  owner: '仓库管理员',
  approver: '审批人',
  dateRange: '生效日期',
  type: '仓库类型',
  name2: '任务名',
  url2: '任务描述',
  owner2: '执行人',
  approver2: '责任人',
  dateRange2: '生效日期',
  type2: '任务类型',
};
const defaultData: DataSourceType[] = [
  // {
  //   id: 624748504,
  //   identification: '活动名称一',
  //   readonly: '活动名称一',
  //   decs: '这个活动真好玩',
  //   state: 'open',
  //   created_at: '1590486176000',
  //   update_at: '1590486176000',
  // },
  // {
  //   id: 624691229,
  //   identification: '活动名称二',
  //   readonly: '活动名称二',
  //   decs: '这个活动真好玩',
  //   state: 'closed',
  //   created_at: '1590481162000',
  //   update_at: '1590481162000',
  // },
];
const TechnicalSupportDetail: React.FC<{}> = () => {
  const actionListRef = useRef<
    FormListActionType<{
      name: string;
    }>
  >();
  const location = useLocation();
  const [formTitle, setFormTitle] = useState('新建技术支持'); //
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  // 表格数据
  const [dataSource, setDataSource] = useState<DataSourceType[]>([]);
  const [formDisabled, setFormDisabled] = useState(false); //设置表单禁用
  const [finished, setfinished] = useState(0);

  const [supportItems, setSupportItems] = useState([]);

  const ischecked = false;
  const [orderInfo, setOrderInfo] = useState();
  const [orderId, setOrderId] = useState('');
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const access = useAccess();

  const hiddenEngId = () => {
    return access.aperatorFilter('hiddenEngId') ? true : false;
  };

  const hiddenSolution = () => {
    return access.aperatorFilter('hiddenSolution') ? true : false;
  };

  useEffect(() => {
    let user = {};

    (async () => {
      if (location.query.id !== undefined && location.query.id !== null) {
        const result = await getTechnicalSupportsById({ id: location.query.id });

        setOrderInfo(result?.data?.salesOrderInfo);
        setFormDisabled(true);
        setSupportItems(result?.data?.technicalSupportItemExList);

        result?.data?.technicalSupportItemExList.map((item) => actionListRef.current.add(item));

        user = result?.data?.userEx;

        setOrderId(result?.data?.salesOrderInfo.id);
        setfinished(result?.data?.isFinished);

        formRef?.current?.setFieldsValue({
          afterSalesNeedInfoId: {
            label: result?.data?.salesOrderInfo.order,
            value: result?.data?.salesOrderInfo.id,
          },

          engineerId: { label: user?.name, value: user?.id },
          // technicalTitle: result?.data?.technicalTitle,
          // technicalText: result?.data?.technicalText,
          // technicalSolution: result?.data?.technicalSolution,
        });
      }
    })();
    waitOrder();
  }, []);

  console.log(location.query.id, '--location.query.id---');
  const formAdd = location.query.id === null || location.query.id === undefined ? true : false;

  /**
   * 穿梭框的数据设置
   */

  const waitOrder = async () => {
    if (location.query.orderId !== undefined && location.query.orderId !== null) {
      let resultSalesId = {};
      resultSalesId = await getAfterSalesNeedInfoDetailById({ id: location.query.orderId });
      setOrderId(location.query.orderId);

      formRef?.current?.setFieldsValue({
        afterSalesNeedInfoId: {
          label: resultSalesId?.data?.identification,
          value: location.query.orderId,
        },
      });
    }
  };
  const formRef = useRef<
    ProFormInstance<{
      name: string;
      company?: string;
      useMode?: string;
    }>
  >();

  const handleSubmit = async () => {
    if (formTitle == '新建技术支持') {
      await addAfterSalesNeedInfo(form.getFieldsValue());
    } else {
      await updateAfterSalesNeedInfo(form.getFieldsValue());
    }

    message.success('添加成功');
    setModalVisit(false);
    // 这个爆红不用管(从新加载页面)
    actionRef.current.reload();
  };
  const [error, setError] = useState<ErrorField[]>([]);
  const getErrorInfo = (errors: ErrorField[]) => {
    const errorCount = errors.filter((item) => item.errors.length > 0).length;

    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = (fieldKey: string) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null;
      }
      const key = err.name[0] as string;
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <CloseCircleOutlined className={styles.errorIcon} />
          <div className={styles.errorMessage}>{err.errors[0]}</div>
          <div className={styles.errorField}>{fieldLabels[key]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger: HTMLElement) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode as HTMLElement;
            }
            return trigger;
          }}
        >
          <CloseCircleOutlined />
        </Popover>
        {errorCount}
      </span>
    );
  };

  const onFinish = async (values: Record<string, any>) => {
    console.log(values, '-values--');
    try {
      //新增
      let result = null;

      if (!formDisabled) {
        result = await addTechnicalsSupport({
          id: values.id,
          identification: null,
          technicalSupportId: values.technicalSupportId,
          afterSalesNeedInfoId: values.afterSalesNeedInfoId.value,
          engineerId: values.engineerId.value,
          // isFinished: finished === 2 ? 0 : finished,
          // technicalTitle: values.technicalTitle,
          // technicalText: values.technicalText,
          // technicalSolution: values.technicalSolution,
          technicalSupportItemDtoList: values.technicalSupportItems.map((item) => {
            item.isFinished ? (item.isFinished = 1) : (item.isFinished = 0);
            return item;
          }),
        });
      } else {
        result = await updateTechnicalsSupport({
          id: location.query.id,
          afterSalesNeedInfoId: orderInfo.order,
          engineerId: values.engineerId.value,
          technicalSupportId: values.technicalSupportId,
          // isFinished: finished === 2 ? 0 : finished,
          // technicalTitle: values.technicalTitle,
          // technicalText: values.technicalText,
          // technicalSolution: values.technicalSolution,
          technicalSupportItemDtoList: values.technicalSupportItems.map((item) => {
            item.isFinished ? (item.isFinished = 1) : (item.isFinished = 0);
            return item;
          }),
        });
      }

      if (result !== null && result !== undefined) {
        message.success('提交成功');
        history.push({
          pathname: `/sales/technicalSupport`,
        });
      }
    } catch {
      //
    }
  };

  const onTempSave = async () => {
    const values = formRef.current?.getFieldsFormatValue?.();
    try {
      //新增
      let result = null;
      debugger;
      if (!formDisabled) {
        result = await addTechnicalSupport({
          id: values.id,
          identification: null,
          technicalSupportId: values.technicalSupportId,
          afterSalesNeedInfoId: values.afterSalesNeedInfoId.value,
          engineerId: values.engineerId.value,
          isFinished: 2,
          technicalTitle: values.technicalTitle,
          technicalText: values.technicalText,
          technicalSolution: values.technicalSolution,
        });
      } else {
        result = await updateTechnicalSupport({
          id: location.query.id,
          engineerId: values.engineerId.value,
          isFinished: 2,
          technicalTitle: values.technicalTitle,
          technicalText: values.technicalText,
          technicalSolution: values.technicalSolution,
        });
      }
      console.log(result + 'rrrrr');
      if (result !== null && result !== undefined) {
        message.success('提交成功');
        history.push({
          pathname: `/sales/technicalSupport`,
        });
      }
    } catch {
      //
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    setError(errorInfo.errorFields);
  };
  // const onChange = (checked: boolean) => {
  //   console.log(`switch to ${checked}`);
  //   checked ? setfinished(1) : setfinished(0);
  // };

  const isCreat = () => {
    return (location.query.id !== undefined && location.query.id !== null) ||
      (location.query.orderId !== undefined && location.query.orderId !== null)
      ? false
      : true;
  };

  /**
   * 穿梭框的数据设置
   */

  return (
    <ProForm
      layout="vertical"
      // hideRequiredMark
      submitter={{
        render: (props, dom) => {
          return (
            <FooterToolbar>
              {dom}
              <Button htmlType="button" key="edit" onClick={onTempSave}>
                保存
              </Button>
            </FooterToolbar>
          );
        },
      }}
      formRef={formRef}
      onFinish={onFinish}
      onFinishFailed={onFinishFailed}
    >
      <PageHeaderWrapper title={false} breadcrumb={undefined}>
        <Card title="技术支持详情" className={styles.card} bordered={false}>
          <Row gutter={16}>
            <Col lg={6} md={12} sm={24}>
              <ProFormSelect
                fieldProps={{
                  labelInValue: true,
                  //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                  onChange: (val, val2) => {},
                }}
                label="设备信息编号"
                name="afterSalesNeedInfoId"
                showSearch
                disabled={!isCreat()}
                rules={[{ required: true, message: '请输入设备信息编号！' }]}
                request={async (para) => {
                  if (
                    (location.query.id !== undefined && location.query.id !== null) ||
                    (location.query.orderId !== undefined && location.query.orderId !== null)
                  ) {
                  } else {
                    const result = await afterSalesNeedList({ blurry: para.keyWords });
                    return result.data.map((item) => {
                      return { label: item.identification, value: item.id, object: item };
                    });
                  }
                }}
              />
            </Col>

            <Col lg={{ span: 6 }} md={{ span: 12 }} sm={24}>
              <ProFormSelect
                fieldProps={{
                  labelInValue: true,
                  //这里使用了select的onChange方法，必须使用这样的写法来进行调用onChange方法
                  onChange: (val, val2) => {
                    console.log(val, val2);
                  },
                }}
                request={async (para) => {
                  {
                    const result = await engineerList({ blurry: para.keyWords });
                    return result.data.map((item) => {
                      // if(item?.roleInfos.includes('ROLE_002'))
                      {
                        console.log('-----' + item);
                        return { label: item.name, value: item.id, object: item };
                      }
                    });
                  }
                }}
                rules={[
                  {
                    required: true,
                    message: '请输入标题!',
                  },
                ]}
                initialValue={formAdd ? { label: '未指定', value: '' } : {}}
                name="engineerId"
                label="工程师"
                hidden={hiddenEngId()}
              />
            </Col>
          </Row>
          {/* <Row gutter={16}>
            <Col lg={{ span: 8 }} md={{ span: 16 }} sm={24}>
              <ProFormTextArea
                name="technicalTitle"
                label="标题:"
                rules={[
                  {
                    required: true,
                    message: '请输入标题!',
                  },
                ]}
                placeholder="标题"
                fieldProps={{ width: '100%', showCount: true, maxLength: 20, rows: 1 }}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={{ span: 18 }} md={{ span: 12 }} sm={24}>
              <ProFormTextArea
                name="technicalText"
                label="技术问题"
                rules={[
                  {
                    required: true,
                    message: '请输入您遇到的问题!',
                  },
                ]}
                placeholder="技术问题"
                fieldProps={{ width: '100%', showCount: true, rows: 8 }}
              />
            </Col>
          </Row>
          <Row gutter={16}>
            <Col lg={{ span: 18 }} md={{ span: 12 }} sm={24}>
              <ProFormTextArea
                name="technicalSolution"
                label="解决方法"
                placeholder="解决方法"
                hidden={hiddenSolution() && finished !== 1}
                disabled={hiddenSolution()}
              />
            </Col>
          </Row>

          <Row gutter={16}>
            <Col lg={{ span: 18 }} md={{ span: 12 }} sm={24}>
              <FormItem>
                <Switch
                  checked={finished === 1}
                  disabled={hiddenSolution()}
                  checkedChildren="完成"
                  unCheckedChildren="未完成"
                  // onChange={onChange}
                />
              </FormItem>
            </Col>
          </Row> */}
        </Card>

        <ProFormList
          name="technicalSupportItems"
          actionRef={actionListRef}
          label="技术支持问题"
          creatorButtonProps={{
            creatorButtonText: '添加问题',
          }}
          min={1}
          copyIconProps={false}
          itemRender={({ listDom, action }, { index }) => (
            <ProCard
              bordered
              style={{ marginBlockEnd: 8 }}
              title={`问题${index + 1}`}
              extra={action}
              bodyStyle={{ paddingBlockEnd: 0 }}
            >
              {listDom}
            </ProCard>
          )}
          // creatorRecord={{ name: '', items: [{ name: '' }] }}
          initialValue={supportItems}
        >
          <ProFormTextArea
            name="technicalTitle"
            label="标题:"
            rules={[
              {
                required: true,
                message: '请输入标题!',
              },
            ]}
            placeholder="标题"
            fieldProps={{ width: '100%', showCount: true, maxLength: 20, rows: 1 }}
          />
          <ProFormTextArea
            name="technicalText"
            label="技术问题"
            rules={[
              {
                required: true,
                message: '请输入您遇到的问题!',
              },
            ]}
            placeholder="技术问题"
            fieldProps={{ width: '100%', showCount: true, rows: 8 }}
          />
          <FormItem>
            <ProFormSwitch
              name="isFinished"
              disabled={hiddenSolution()}
              checkedChildren="完成"
              unCheckedChildren="未完成"
              // onChange={onChange}
            />
          </FormItem>
        </ProFormList>
      </PageHeaderWrapper>
    </ProForm>
  );
};

export default TechnicalSupportDetail;
